#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstring>
#include <sstream>

#define INPUT_PATH_NAME "/tmp/node1_to_node2.tmp"
#define OUTPUT_PATH_NAME "/tmp/node2_to_node1.tmp"

// node2
int main() {
  int fin = open(INPUT_PATH_NAME, O_RDONLY);
  int fout = open(OUTPUT_PATH_NAME, O_WRONLY);

  char buffer[1024]; // 定义接受的文件大小，可以设大点，1024*1024*n
  while (true) {
    memset(buffer, 0, sizeof(buffer));
    if (read(fin, buffer, sizeof(buffer)) <= 0) {
      printf("node1 closed, exit!\n");
      break;
    }
    printf("receive: %s\n", buffer);

    std::stringstream ss;
    ss << "I'm fine, thx!";
    if (write(fout, ss.str().c_str(), ss.str().length() + 1) <= 0) {
      break;
    }
    printf("send   : %s\n", ss.str().c_str());
    sleep(1);
  }
  close(fin);
  close(fout);
  return 0;
}